package com.learn.dict.handler;

import cn.hutool.cache.CacheUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import com.learn.dict.domain.vo.DictDataOptions;
import com.learn.dict.handler.dictdata.IDictDataHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 功能描述: 字典表加载 <br/>
 *
 * @author: MI
 * @email: 448341911@qq.com
 * @createDate: 2023/10/22 22:29
 * @updateUser: MI
 * @updateDate: 2023/10/22 22:29
 * @updateRemark: 修改内容
 * @version: v1.0
 */
@Component
public class DictDataHandler extends AbstractDictHandler {

    @Resource
    private DictHandlerAware dictHandlerAware;

    @Override
    public void loadDictCache() {
        cacheData = CacheUtil.newFIFOCache(10000);
    }

    @Override
    public List<DictDataOptions> getDictDataOptions(String typeCode) {
        List<DictDataOptions> dictDataOptions = cacheData.get(typeCode);
        // 如果缓存中不存在，则说明可能失败，再次从数据库中查询
        if (CollUtil.isEmpty(dictDataOptions)) {
            List<DictDataOptions> dictDataOptionsList = getDictDataHandler().getDictDataOptions(typeCode);
            if (CollUtil.isEmpty(dictDataOptionsList)) {
                put(typeCode, dictDataOptionsList);
            } else {
                return ListUtil.empty();
            }
        }
        return cacheData.get(typeCode);
    }

    @Override
    public void reloadDictCache(String typeCode) {
        // 加载字典缓存
        remove(typeCode);
        List<DictDataOptions> dictDataList = getDictDataHandler().getDictDataOptions(typeCode);
        if (CollUtil.isNotEmpty(dictDataList)) {
            put(typeCode, dictDataList);
        }

    }

    private IDictDataHandler getDictDataHandler() {
        return dictHandlerAware.getDictHandler();
    }

}
